package other.edan.erp.k3;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.data.model.SyncConfig__c;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.OperateResult;
import com.rkhd.platform.sdk.service.XoqlService;
import org.apache.commons.lang.StringUtils;
import other.edan.erp.utils.HCDateUtils;
import other.edan.erp.utils.HCXObjectService;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Description: 同步功能方法
 * @Author: 黎炎松
 * @Date: 2024/8/30 15:31
 */
public class SyncSuper {
    private static final Logger LOGGER = LoggerFactory.getLogger();


    public static void main(String[] args) throws ParseException {
        Long dateVal = new SyncSuper().getDateVal("2021-11-26 00:00:00.0", 2);
        System.out.println("dateVal = " + dateVal);
    }

    /**
     * 获取CRM数据map
     * @param mapFlag
     * @param valKey 值的key
     * @param erpDataList erp数据
     * @return
     * @throws ApiEntityServiceException
     */
    public Map<String, Long> getCrmDataMap(String mapFlag, String valKey, List<JSONObject> erpDataList) throws ApiEntityServiceException {
        Map<String, Long> crmDataMap = new HashMap<>();

        String erpVals = erpDataList.stream().filter(v -> StringUtils.isNotBlank(v.getString(valKey))).map(v -> "'" + v.getString(valKey) + "'").distinct().collect(Collectors.joining(","));
        if (StringUtils.isBlank(erpVals)) {
            return crmDataMap;
        }

        String sql = "";
        String numberKey = "";
        switch (mapFlag) {
            case "user":
                // 用户 只匹配用户姓名
                sql = String.format("select id,name from user where name in (%s)", erpVals);
                numberKey = "name";
                break;
            case "account":
                // 客户
                sql = String.format("select id,K3Code__c from account where K3Code__c in (%s)", erpVals);
                numberKey = "K3Code__c";
                break;
            case "product":
                // 产品
                sql = String.format("select id,FNumber__c from product where FNumber__c in (%s)", erpVals);
                numberKey = "FNumber__c";
                break;
            case "order":
                // 订单
                sql = String.format("select id,po from order where po in (%s)", erpVals);
                numberKey = "po";
                break;
            case "k3CodeOrder":
                // 根据K3订单code获取订单订单
                sql = String.format("select id,k3Billno__c from order where k3Billno__c in (%s)", erpVals);
                numberKey = "k3Billno__c";
                break;
            case "orderProductById":
                // 根据id获取订单明细
                sql = String.format("select id from orderProduct where id in (%s)", erpVals);
                numberKey = "id";
                break;
            case "snCode":
                // SN码
                sql = String.format("select id,snCode__c from snCode__c where snCode__c in (%s)", erpVals);
                numberKey = "snCode__c";
                break;
            case "saleOut":
                // 销售出库
                sql = String.format("select id,name from salesOutReceipt__c where name in (%s)", erpVals);
                numberKey = "name";
                break;
            case "saleInvoice":
                // 销售发票
                sql = String.format("select id,name from salesInvoice__c where name in (%s)", erpVals);
                numberKey = "name";
                break;
            case "logistics":
                // 物流信息
                sql = String.format("select id,name from logisticsInfo__c where name in (%s)", erpVals);
                numberKey = "name";
                break;
            case "k3depart":
                // 物流信息
                sql = String.format("select id,departId__c from k3Department__c where departId__c in (%s)", erpVals);
                numberKey = "departId__c";
                break;
        }

        String finalNumberKey = numberKey;
        crmDataMap = XoqlService.instance().query(sql).getRecords().stream().collect(Collectors.toMap(e -> e.getString(finalNumberKey), e1 -> e1.getLong("id"), (e, e1) -> e));
        LOGGER.info("crmDataMap: " + mapFlag + " ==> " + crmDataMap.size());

        return crmDataMap;
    }

    /**
     * 根据标识获取系统配置
     * @param syncKey
     * @return
     */
    public SyncConfig__c getSyncConfig(String syncKey)  {
        String sql = String.format("select id,lastSyncTime__c from syncConfig__c where syncKey__c = '%s'", syncKey);
        SyncConfig__c syncConfig = HCXObjectService.queryOne(sql);

        // 配置为空，开始结束-1
        String endDate = HCDateUtils.dateToString(new Date(), HCDateUtils.FORMATTIME); // 同步结束时间
        String startDate = "";
        if (syncConfig == null || syncConfig.getLastSyncTime__c() == null) {
            if (syncConfig == null) syncConfig = new SyncConfig__c();
            startDate = HCDateUtils.getDaysBeforeString(1, HCDateUtils.FORMATTIME);
        } else {
            startDate = syncConfig.getLastSyncTime__c();
        }

        syncConfig.setLastSyncTime__c(endDate);
        syncConfig.setAttribute("startDate", startDate);
        syncConfig.setAttribute("endDate", endDate);
        LOGGER.info( " syncConfig = " + syncConfig);
        return syncConfig;
    }

    /**
     * 修改同步配置
     * @param syncConfig
     */
    public void upSyncConfig(SyncConfig__c syncConfig) throws ParseException {
        if (syncConfig == null) {
            return;
        }

        // 更新同步配置 (只修改上次更新时间字段)
        SyncConfig__c upSyncConfig = new SyncConfig__c();
        upSyncConfig.setId(syncConfig.getId());
        //upSyncConfig.setLastSyncTime__c(syncConfig.getLastSyncTime__c());
        upSyncConfig.setLastSyncTime__c(HCDateUtils.longToString(System.currentTimeMillis(), HCDateUtils.FORMATTIME));
        HCXObjectService.update(upSyncConfig);
    }

    /**
     * 获取是或否 1：是 2：否
     * @param str
     * @return
     */
    public Integer getIsYes(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }

        int isYes = 2;
        if (str.equals("是")) {
            isYes = 1;
        }
        return isYes;
    }


    /**
     * 获取时间戳
     * @param dateTimeString
     * @return type 日期类型 1: 2022-01-20T00:00:00.000+08:00   2: 2022-01-20 00:00:00.0
     */
    public Long getDateVal(String dateTimeString, int type) throws ParseException {
        if (StringUtils.isBlank(dateTimeString)) {
            return null;
        }
        if (type == 1) {
            ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateTimeString, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
            // 转换为时间戳（毫秒）
            return zonedDateTime.toInstant().toEpochMilli();
        } else if (type == 2) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
            return formatter.parse(dateTimeString).getTime();
        } else {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            return formatter.parse(dateTimeString).getTime();
        }
    }

    public Integer getIntVal(String val) {
        if (StringUtils.isNotBlank(val)) {
            return Integer.valueOf(val);
        }
        return null;
    }

    /**
     * 除
     * @param v1
     * @param v2
     * @return
     */
    public static double bgDivide(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2).doubleValue();
    }

}
